package com.android.lovingpet;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;

import com.android.lovingpet.bean.Account;
import com.android.lovingpet.bean.Team;
import com.android.lovingpet.common.Back;
import com.android.lovingpet.common.FileModel;
import com.android.lovingpet.common.Model;
import com.android.lovingpet.common.UserModel;
import com.android.lovingpet.util.CallbackStore;
import com.android.lovingpet.util.HttpUtil;
import com.android.lovingpet.util.MyHttp;
import com.android.lovingpet.util.ParseMD5;
import com.android.lovingpet.util.URLStore;
import com.android.lovingpet.util.Utility;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class SignModel {
    /**
     * @param mode 0: 注册 1: 登录
     * @param userName 必须是手机号
     * @param password 未加密的密码
     * @param userType 	0：组织 1：个人
     */
    public void sign(int mode, String userName, String password, int userType, Back back) {
        Map<String, String> params = new HashMap<>();
        params.put("userName", userName);
        params.put("password", ParseMD5.parseStrToMd5U16(password));
        params.put("userType", userType + "");
        String url = URLStore.USER_LOGIN;
        if (mode == 0) {
            url = URLStore.USER_REGISTER;
        }
        HttpUtil.postAsync(null, url, params, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                back.onFailure(HttpUtil.getFailureMeg());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                try {
                    JSONObject object = new JSONObject(str);
                    int status = object.getInt("code");
                    if (status != 0) {
                        back.onFailure(HttpUtil.getCodeString(status));
                    } else {
                        String cookieval = response.header("Set-Cookie");
                        String sessionId = cookieval.substring(0,cookieval.indexOf(";"));
                        Utility.setJSessionId(sessionId);
                        Log.d("zhuce",sessionId);
                        int id = object.getInt("id");
                        Utility.setRealId(id);
                        Utility.setUserType(userType);
                        if (mode == 0) {
                            back.onSuccess(null);
                        } else {
                            getInfo(id, userType, back);
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void sendCode(String phone, Back back) {
        Map<String, String> params = new HashMap<>();
        params.put("phone", phone);
        HttpUtil.postAsync(null, URLStore.USER_AUTH_PHONE, params, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                back.onFailure(HttpUtil.getFailureMeg());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String str = response.body().string();
                try {
                    JSONObject object = new JSONObject(str);
                    int status = object.getInt("code");
                    if (status != 0) {
                        back.onFailure(HttpUtil.getCodeString(status));
                    } else {
                        String cookieval=response.header("Set-Cookie");
                        String sessionId=cookieval.substring(0,cookieval.indexOf(";"));
                        Bundle bundle = new Bundle();
                        bundle.putString("JSessionId", sessionId);
                        back.onSuccess(bundle);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public void authCode(String sessionId, String phone, String code, String formTime, Back back) {
        Map<String, String> params = new HashMap<>();
        params.put("phone", phone);
        params.put("code", code);
        params.put("fromTime", formTime);
        HttpUtil.postAsync(sessionId, URLStore.USER_AUTH_SUCCESS, params, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                back.onFailure(HttpUtil.getFailureMeg());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    JSONObject object = new JSONObject(response.body().string());
                    int status = object.getInt("code");
                    if (status == 0 || status == 8) {
                        back.onSuccess(null);
                    } else {
                        back.onFailure(HttpUtil.getCodeString(status));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     *
     * @param gender 0：女 1： 男
     */
    public void commitPersonInfo(int id, int userType, File head, String name, int gender, Back back) {
        Map<String, String> params = new HashMap<>();
        params.put("name", name);
        params.put("gender", gender + "");
        HttpUtil.postAsync(Utility.getJSessionId(), URLStore.PERSON_INFO_SIMPLE, params, new CallbackStore.CallbackImpl<Back>(back) {
            @Override
            public void onResponse(String json) {
                uploadHead(id, userType, head, back);
            }
        });
    }

    public void commitTeamInfo(int id, File image, String name, String address, String ETime, String nature, String HName, String HPhone, String email, String OPhone, String code, Back back) {
        Map<String, String> params = new HashMap<>();
        params.put("name", name);
        params.put("address", address);
        params.put("etime", ETime);
        params.put("nature", nature);
        params.put("hName", HName);
        params.put("hPhone", HPhone);
        params.put("email", email);
        params.put("oPhone", OPhone);
        params.put("codeNumber", code);
        MyHttp.getInstance().postAsync(Utility.getJSessionId(), URLStore.TEAM_INFO_SIMPLE, params, new CallbackStore.CallbackImpl<Back>(back) {
            @Override
            public void onResponse(String json) throws JSONException {
                uploadHead(id, 0, image, back);
            }
        });
    }

    private void uploadHead(int id, int userType, File head, Back back) {
        FileModel.getInstance().uploadImage(id, userType, head, new Back() {
            @Override
            public void onFailure(String msg) {
                back.onFailure(msg);
            }

            @Override
            public void onSuccess(@Nullable Bundle bundle) {
                getInfo(id, userType, back);
            }
        });

    }

    private void getInfo(int id, int userType, Back back) {
        if (userType == 0) {
            UserModel.getInstance().getTeamInfo(id, new FileModel.FileBack() {
                private Team team;

                @Override
                public void loadSuccess(String url) {
                    team.setImage(url);
                    Utility.setTeam(team);
                    back.onSuccess(null);
                }

                @Override
                public void onFailure(String msg) {
                    back.onFailure(msg);
                }

                @Override
                public void onSuccess(@Nullable Bundle bundle) {
                    team = bundle.getParcelable("team");
                }
            });
        } else {
            UserModel.getInstance().getInfo(id, new FileModel.FileBack() {
                private Account account;

                @Override
                public void loadSuccess(String url) {
                    account.setHead(url);
                    Utility.setAccount(account);
                    back.onSuccess(null);
                }

                @Override
                public void onFailure(String msg) {
                    back.onFailure(msg);
                }

                @Override
                public void onSuccess(@Nullable Bundle bundle) {
                    account = bundle.getParcelable("account");
                }
            });
        }
    }
}
